/**
 * Copyright (C) Skywares Information Technology, LTD. 
 * All Rights Reserved.
 *
 * OrderService.java created on 2020年2月4日 下午7:28:00 by Lyon Lu 
 */
package com.mvc.server.miaosha.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mvc.server.component.RedisService;
import com.mvc.server.miaosha.dao.OrderDao;
import com.mvc.server.miaosha.pojo.MiaoshaOrder;
import com.mvc.server.miaosha.pojo.MiaoshaUser;
import com.mvc.server.miaosha.pojo.OrderInfo;
import com.mvc.server.miaosha.redis.OrderKey;
import com.mvc.server.miaosha.vo.GoodsVo;

/**
 * <pre>
 * Description:
 * 
 * @author Lyon Lu
 * @date 2020年2月4日 下午7:28:00
 *
 * </pre>
 */
@Service
public class OrderService {
	
	@Resource
	private OrderDao orderDao;

	@Resource
	private RedisService redisService;
	
	/**
	 * Description:
	 * 		method description here
	 * @param userId
	 * @param goodsId
	 * @return MiaoshaOrder      
	 * @throws                                 
	 */
	public MiaoshaOrder getCacheMiaoshaOrderByUserIdGoodsId(Long userId, long goodsId) {
		
		//return orderDao.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
		
		return redisService.get(OrderKey.getOrderByUserIdAndGoodsId, getOrderKeySuffix(userId, goodsId), MiaoshaOrder.class);
	}
	
	/**
	 * Description:
	 * 		method description here
	 * @param @param userId
	 * @param @param goodsId
	 * @param @return
	 * @return String      
	 * @throws                                 
	 */
	private String getOrderKeySuffix(Long userId, long goodsId) {
		
		return String.valueOf(userId) + String.valueOf(goodsId);
	}

	@Transactional
	public OrderInfo createOrder(MiaoshaUser user, GoodsVo goods) {
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setCreateDate(new Date());
		orderInfo.setDeliveryAddrId(0L);
		orderInfo.setGoodsCount(1);
		orderInfo.setGoodsId(goods.getId());
		orderInfo.setGoodsName(goods.getGoodsName());
		orderInfo.setGoodsPrice(goods.getMiaoshaPrice());
		orderInfo.setOrderChannel(1);
		orderInfo.setStatus(0);
		orderInfo.setUserId(user.getId());
		orderDao.insert(orderInfo);
		MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
		miaoshaOrder.setGoodsId(goods.getId());
		miaoshaOrder.setOrderId(orderInfo.getId());
		miaoshaOrder.setUserId(user.getId());
		orderDao.insertMiaoshaOrder(miaoshaOrder);
		
		redisService.set(OrderKey.getOrderByUserIdAndGoodsId, getOrderKeySuffix(user.getId(), goods.getId()), miaoshaOrder);
		
		return orderInfo;
	}

	public List<MiaoshaOrder> getAllMiaoshaOrdersByGoodsId(long goodsId) {
		return orderDao.listByGoodsId(goodsId);
	}
}
